package com.agileai.wm.module.workmanage.handler;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.MasterSubListHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;
import com.agileai.wm.common.FileExportHelper;
import com.agileai.wm.cxmodule.WmWeekManage;

public class WmWeekManageListHandler
        extends MasterSubListHandler {
    public WmWeekManageListHandler() {
        super();
        this.editHandlerClazz = WmWeekManageEditHandler.class;
        this.serviceId = buildServiceId(WmWeekManage.class);
    }
	public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		this.setAttributes(param);
		String currentUserId = param.get("currentUserId");
		if (StringUtil.isNullOrEmpty(currentUserId)){
			User user = (User)getUser();
			currentUserId = user.getUserId();
		}
		param.put("currentUserId",currentUserId);
		List<DataRow> rsList = getService().findMasterRecords(param);
		this.setRsList(rsList);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
    	FormSelect stateSelect = FormSelectFactory.create("WEEK_WORK_STATE")
                .addSelectedValue(getOperaAttributeValue("WW_STATE","INITIALISE")); 
        setAttribute("WW_STATE",stateSelect);
        this.initMappingItem("WW_STATE", stateSelect.getContent());
    }

    protected void initParameters(DataParam param) {
        initParamItem(param, "PRE_DESCRIBE", "");
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes"})
	@PageAction
   	public ViewRenderer exportExcelFile(DataParam param) {
    	User user = (User) this.getUser();
    	param.put("currentUserId", user.getUserId());
		param.put("USER_ID",user.getUserId());
		List<DataRow> weekWorkRecord = getService().findMasterRecords(param);
    	List<DataRow> personalWmWeekContent = (List<DataRow>) getService().getPersonalWmWeek(param); 
    	List<DataRow> WmWeekContent =new ArrayList<DataRow>();
    	
    	for(int k=0;k<weekWorkRecord.size();k++){
    		DataRow dataRow =weekWorkRecord.get(k);
    		String WW_ID=dataRow.getString("WW_ID");
    		DataRow dataRow3 = new DataRow();
    		String ENTRY_DESCRIBE = "";
    		String ENTRY_FINISH = "";
    		for(int m=0;m<personalWmWeekContent.size();m++){
    			DataRow dataRow2 =personalWmWeekContent.get(m);
    			String ID =dataRow2.getString("WW_ID");
    			if(WW_ID.equals(ID) && m==personalWmWeekContent.size()-1){
    				ENTRY_FINISH+=dataRow2.getString("ENTRY_FINISH");
    				ENTRY_DESCRIBE+=dataRow2.getString("ENTRY_DESCRIBE");
    				dataRow3=dataRow2;
    			}else if (WW_ID.equals(ID) && m<personalWmWeekContent.size()-1){
    				ENTRY_FINISH+=dataRow2.getString("ENTRY_FINISH")+",";
    				ENTRY_DESCRIBE+=dataRow2.getString("ENTRY_DESCRIBE")+",";
    				dataRow3=dataRow2;
    			}
    		}
    		dataRow3.put("ENTRY_DESCRIBE", ENTRY_DESCRIBE);
    		dataRow3.put("ENTRY_FINISH", ENTRY_FINISH);
    		WmWeekContent.add(dataRow3);
    	}
    	
		String fileName =user.getUserName()+"周报.xls";
		List<HashMap> logs = new ArrayList<HashMap>();
		int index=0;
		for (int i=0;i < WmWeekContent.size();i++){
			DataRow dataRow = WmWeekContent.get(i);
			HashMap log = new HashMap();
			Date WT_BEGIN =(Date) dataRow.get("WT_BEGIN");
			Date WT_END =(Date) dataRow.get("WT_END");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
			log.put("startTime",sdf.format(WT_BEGIN));
			log.put("endTime",sdf.format(WT_END));
			
			List<HashMap> logContent = new ArrayList<HashMap>();
			String ENTRY_DESCRIBE = dataRow.getString("ENTRY_DESCRIBE");
			String ENTRY_FINISH = dataRow.getString("ENTRY_FINISH");
			String[] sourceFinshArray = ENTRY_FINISH.split(",");
			String[] sourceStrArray = ENTRY_DESCRIBE.split(",");
			int length=sourceStrArray.length;
			int k=0;
			for(int j=0;j<sourceStrArray.length;j++){
				HashMap contentMap = new HashMap();
				if("".equals(sourceStrArray[j]) || sourceStrArray[j]==null){
					length=length-1;
				}else{
					if(null == sourceStrArray[j] || "null".equals(sourceStrArray[j])){
						contentMap.put("text","");
					}else{
						contentMap.put("text",sourceStrArray[j]);
					}
					
					if("0".equals(sourceFinshArray[k])){
						contentMap.put("status", "未完成");
					}else if("1".equals(sourceFinshArray[k])){
						contentMap.put("status", "已完成");
					}else{
						contentMap.put("status", "");
					}
					
					k++;
					logContent.add(contentMap);
				}
				
			}
			log.put("contentList", logContent);
			log.put("rowIndex", 4*i+3+index);
			log.put("index", i+1);
			index+=sourceStrArray.length;
			String userName = user.getUserName();
			String userId = user.getUserId();
			DataParam groupParam = new DataParam();
			groupParam.put("userId", userId);
			DataRow groupRow = getService().findGroupRecord(groupParam);
			String groupName = groupRow.getString("GRP_NAME");
			log.put("userName", userName);
			log.put("groupName", groupName);
			logs.add(log);
		}
		exportFile(logs, fileName);
       	return new NullRenderer();
   	}
    
    @SuppressWarnings({ "unchecked", "rawtypes"})
	private void exportFile(Object model, String fileName) {
		try {
			FileExportHelper fileStreamHelper = new FileExportHelper(request, response);
			String templateDir = fileStreamHelper.getTemplateDirPath();
			String templateFile = "/SelfWeekReport.ftl";
			
			HashMap modelMap = new HashMap();
			modelMap.put("logs", model);
			fileStreamHelper.exportFile(templateDir, templateFile, fileName, modelMap,"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    protected WmWeekManage getService() {
        return (WmWeekManage) this.lookupService(this.getServiceId());
    }
}
